<?
class RequireAction extends Action {
  private $_dev = 0;
  private $_uid = 0;
  private $_username = "";
  private $_checkAction=array('publish','save','saveComment');//检查登录状态的action
  //树的构造也用到这个变量
  private $_types = array(
    0=>array(tree_id=>0,tree_pid=>-1,name=>'全部',url=>'/main/public.php/require/lists/tree_id/0'),
    1=>array(tree_id=>1,tree_pid=>0,name=>'会务',url=>'/main/public.php/require/lists/tree_id/1/type/1'),
//    1=>array(tree_id=>1,tree_pid=>0,name=>'活动',url=>'/main/public.php/require/lists/tree_id/1/type/1',
//        sub=>array(
//            1=>array(tree_id=>2,tree_pid=>1,name=>'会务',url=>'/main/public.php/require/lists/tree_id/2/type/1/sub/1'),
//            2=>array(tree_id=>3,tree_pid=>1,name=>'聚会',url=>'/main/public.php/require/lists/tree_id/3/type/1/sub/2')
//        )
//    ),
    3=>array(tree_id=>4,tree_pid=>0,name=>'培训',url=>'/main/public.php/require/lists/tree_id/4/type/3'),
    5=>array(tree_id=>5,tree_pid=>0,name=>'招聘求职',url=>'/main/public.php/require/lists/tree_id/5/type/5',
        sub=>array(
            1=>array(tree_id=>6,tree_pid=>5,name=>'招聘',url=>'/main/public.php/require/lists/tree_id/6/type/5/sub/1'),
            2=>array(tree_id=>7,tree_pid=>5,name=>'求职',url=>'/main/public.php/require/lists/tree_id/7/type/5/sub/2')
        )
    ),
    7=>array(tree_id=>8,tree_pid=>0,name=>'EHS需求',url=>'/main/public.php/require/lists/tree_id/8/type/7',
        sub=>array(
            1=>array(tree_id=>9,tree_pid=>8,name=>'产品',url=>'/main/public.php/require/lists/tree_id/9/type/7/sub/1'),
            2=>array(tree_id=>10,tree_pid=>8,name=>'EHS服务',url=>'/main/public.php/require/lists/tree_id/10/type/7/sub/2'),
            3=>array(tree_id=>11,tree_pid=>8,name=>'工程',url=>'/main/public.php/require/lists/tree_id/11/type/7/sub/3'),
            4=>array(tree_id=>12,tree_pid=>8,name=>'悬赏或招标',url=>'/main/public.php/require/lists/tree_id/12/type/7/sub/4')
        )
    ),
  );
  function _initialize() {
    $this->_dev = C("DEV_FLAG");
    $this->_uid = empty($_SESSION['admin_id'])?$_COOKIE["tpxslmluserid"]:$_SESSION['admin_id'];
    $this->_username = empty($_SESSION['admin_name'])?$_COOKIE["tpxslmlusername"]:$_SESSION['admin_name'];
    $this->assign('dev', $this->_dev);
    $this->assign("waitSecond", 3);
    $this->assign("istp", 1);//circle-header2中有TP和PHPWIND都用到，加上这个参数进行区别
    if (in_array(ACTION_NAME,$this->_checkAction)) {
      if(!$_COOKIE['tpxslmlusername'] || !$_COOKIE['tpxslmluserid'] || !$_COOKIE['tpxslmlgroupid'] || !$_COOKIE['tpxslmlrnd']) {
        if(empty($_SESSION['isAdmin'])){
		if(empty($_GET['isAjax'])){
		  	$this->assign("jumpUrl", "/pw8/login.php");
        	$this->error("您还没有登陆，请登录");
		}else echo json_encode(array('result'=>01));
		}
      }
    }
  }

  //供求首页
  public function index() {
    $this->_getRequireList(array(1,3,5,7));
    $this->assign('types', $this->_types);
    $this->display();
  }

  //获取供求列表
  private function _getRequireList($types) {
    $m = M('ARequire');
    foreach($types as $k => $type) {
      $list = $m->where('type='.$type.' and status = 1')->order('top desc,pub_time desc')->limit('0,9')->select();
      $this->assign('type_'.$type, $list);
    }
  }

  //判断是否有权利修改该供求信息
  private function _checkEidtAuthority($id,$uid) {
    
    if(!empty($_SESSION['isAdmin']) && $_SESSION['isAdmin']==1)
	  return true;
	else{
	   dump($_SESSION);exit();
    	$m = M('ARequire');
    	$rt = $m->where('id = '.$id.' and uid = '.$uid)->find();
    	$this->assign('jumpUrl', __URL__.'/index/');
    	if ($rt == null) $this->error('你没有权限修改该信息');
	}
  }

  //发布页面
  public function publish() {
    $reginoID = 19;//广东省id，初始化地区是广东省广州市
    $reginoID2 = 165;
    $type = 5;
    $sub = 1;
    $edit = 0;
    $m = M('ARequire');
    //编辑则加入以下数据作为初始化
    if ($_GET['id'] && $_GET['id'] != '' && $_GET['id'] > 0) {
      $id = $_GET['id'];
      $this->_checkEidtAuthority($id,$this->_uid);
      $info = $m->where('id = '.$id)->find();
	  $info['content']=htmlspecialchars(str_replace(array('\\',"\r\n","\n"),array('','',''),$info['content']));
      $this->assign('info',$info);
      $reginoID2 = $info['dq_id'];
      $reginoID = $this->_getRegionLine($reginoID2,1);
      $type = $info['type'];
      $sub = $info['sub'];
      $edit =$_GET['id'];
	  $attach=$this->_getAttachMents($edit);
	  $this->assign('attach',$attach);
    }
    //获取一级地区名称
    $sql = 'select * from a_region where did = 0';
    $list = $m->query($sql);
    $this->assign('region_level_1', $list);
    $list = $m->query('select * from a_region where did = '.$reginoID);
    $this->assign("region_level_2", $list);
    $this->assign("region_id", $reginoID);
    $this->assign('region_id2', $reginoID2);
    $this->assign('type', $type);
    $this->assign('sub', $sub);
    $this->assign('edit', $edit);
    $this->display();
  }

  //保存发布信息
  public function save() {
     $attachID=0;
	 //dump($_FILES);exit();
     if(!empty($_FILES['file']['name'])){
	   	import("ORG.Net.UploadFile");
		$upload = new UploadFile(); // 实例化上传类
		$upload->maxSize  = 3048576 ; // 设置附件上传大小1M
		$upload->subType=date;
		$upload->saveRule=com_create_guid; 
		$upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg','doc','docx','xls','xlsx','rar','zip','pdf'); // 设置附件上传类型
		$upload->savePath =  './PublicFunction/upload/'; // 设置附件上传目录
		if(!$upload->upload()) { // 上传错误提示错误信息
		  $this->error($upload->getErrorMsg());
		  eixt();
		}else{ // 上传成功 获取上传文件信
	 	  $info =  $upload->getUploadFileInfo();
		  $m=M('AAttachments');
	 	  $data['user_id']=$this->_uid;
		  $data['user_name']=$this->_username;
		  $data['related_id']=0;
		  $data['type']='require';
		  $data['up_time']=date('Y-m-d H:i:s');
		  $data['file_name']=$info[0]['name'];
		  //dump($info);
		  //xit($info[0]['savepath'].'/'.$info[0]['savename']);
	      $data['file_path']=$info[0]['savepath'].'/'.$info[0]['savename'];
	  	  $attachID=$m->add($data);
		  //alert($info);
	  }
	 }
	 
    $edit =!empty($_POST['id'])?true:false;
    $m =M('ARequire');
    $data = $_POST;
    unset ($data['__hash__']);
    $data['uid'] = $this->_uid;
    $data['username'] = $this->_username;
	$data['content'] = str_replace('\\','',$data['content']);
	
    if ($edit) {
	  $data['status']=0;
      $rt = $m->save($data);
	  $m=M('AAttachments');
	  $m->save(array('id'=>$attachID,'related_id'=>$_POST['id']));
	  $this->assign('jumpUrl', __URL__.'/index');
	  $this->success('修改成功，需等待管理员重新审核');		
	  // }
    }else {
      $data['pub_time'] = date("Y-m-d H:i:s");
      $data['pub_date'] = date('Y-m-d');
      $rt = $m->add($data);
	  //dump($_FILES);exit();
      if ($rt) {
	    if($attachID){ 
		  $m=M('AAttachments');
	      $m->save(array('id'=>$attachID,'related_id'=>$rt));
		 }
        $this->assign('jumpUrl', __URL__.'/index');
        $this->success('发表成功，请等待审核');
      }
      else $this->error('发表失败，请重新发表');
    }

  }

  //地区下拉框
  public function ajaxChgRegion() {
    $id = $_POST['id'];
    $m = M();
    $sql = 'select * from a_region where did = '.$id;
    $list = $m->query($sql);
    $this->ajaxReturn($list);
  }

  //供求列表
  public function lists() {
    $m = M("ARequire");
    import("@.ORG.Page"); //导入分页类
    $records = 20;//每页多少条记录
    $where = 'status = 1';
    if ($_GET['type'] == 1 || $_GET['type'] == 3 || $_GET['type'] == 5 || $_GET['type'] == 7) $where .= ' and type = '.$_GET['type'];
    if ($_GET['sub'] > 0 && $_GET['sub'] < 5) $where .= ' and sub = '.$_GET['sub'];
    $count = $m->where($where)->count();
    $p = new Page ($count,$records);
    $p->setConfig('header','篇记录');
    $p->setConfig('prev',"上一页");
    $p->setConfig('next','下一页');
    $p->setConfig('first','<<');
    $p->setConfig('last','>>');
    $page = $p->show();
    $list = $m->where($where)->order("top desc,pub_date desc")->limit($p->firstRow.",".$p->listRows)->select();
    $this->assign("count", $count);
    $this->assign("list", $list);
    $this->assign("nowPage",$p->nowPage);
    $this->assign("page", $page );
    $this->assign("records",$records);
    $this->assign('types', $this->_types);
    $this->assign('typesObj',json_encode($this->_types));
    $treeID = $_GET['tree_id'] && $_GET['tree_id'] >=0 ? $_GET['tree_id'] : 0;
    $this->assign('tree_id', $treeID);
    $this->display();
  }

  //具体内容页面
  public function content() {
    $id = $_GET['id'];
    $m = M('ARequire');
	$allowEdit=0;
	
    $content = $m->where('id = '.$id)->find();
	if(!empty($this->_uid) && $this->_uid==$content['uid'])
	 $allowEdit=1;
	 
	$m->setInc('read_num','id='.$id);
	
	//管理员后台登陆后初始化_SESSION['ISADMIN']
	if(!empty($_SESSION['isAdmin']) && $_SESSION['isAdmin']==1)
	 $allowEdit=1; 
	 
	 //dump($_SESSION);
	// exit($this->_uid.'/'.$content['uid']);
	
    if (!$content) {
      $this->assign('jumpUrl', __URL__);
      $this->error('您所查看的信息不存');
	  exit();
    }elseif(!$content['status'] && empty($_SESSION['isAdmin']) ){
	  $this->assign('jumpUrl', __URL__);
      $this->error('您所查看的信息未通过审核');
	  exit();
	}
    $content['region'] = $this->_getRegionLine($content['dq_id']);
	$content['content']=strip_tags($content['content'],'<a><p><br><dl><dt><dd><ul><li><span><table><tbody><thead><style><xml><th><b><tr><td><img>');//去除 除换行符以外的全部标签
	//$content['content']=strip_tags($content['content'],'<p><br><dl><dt><dd><ul><li><span><b><style><xml>');
	//$content['content']=strip_tags($content['content']);
	//$content['content']=htmlspecialchars(str_replace(array('\\','\''),array('','"'),$content['content']));
	//htmlspecialchars($content['content']);
    $content['content'] = htmlspecialchars_decode($content['content']);
	$this->assign('content',$content);//strip_tags($content,'<span><a><div>'));
	//echo htmlspecialchars($content);
    $this->assign('types', $this->_types);
    //获取评论列表
    $ac = A('Comment');
    $commentList = $ac->lists(1,$id);
	$attach=$this->_getAttachMents($id);
	//dump($attach);
	$this->assign('id', $id);
	$this->assign('allowEdit', $allowEdit);
	$this->assign('attach', $attach);
    $this->assign('comment_list', $commentList);
    //获取右边列表
    $this->_getRequireList(array(1,3,5,7));
	
    $this->display();
  }
  
  
  /*
  *  每月课程
  *  @mon 月份参数，无参数表示当前月份
  *  BY 3211
  */
  public function monCourse(){
	 $mon=empty($_GET['mon'])?date('ym'):$_GET['mon']; 
	 $this->display('course'.$mon);
  }
  
  
  //删除对应附件
  public function delAttachAjax(){
     if(!empty($_GET['id'])){
	   $m=M('AAttachments');
	   $item=$m->find($_GET['id']);
	   if($m->where('id='.$_GET['id'])->delete()){
		 echo json_encode(array('result'=>1));
		 //alert($m->getLastSQL());
		 $flag=C('DEV_FLAG');
	     $flag==1?unlink("F:/www/main/".$item['file_path']):unlink("E:/www/main/".$item['file_path']);
		}
	   else 
	     echo json_encode(array('result'=>0));
	 }else{
	   echo json_encode(array('result'=>02));
	 }
	 //alert($m->getLastSQL());
  }
  

  //根据地区id，获取整条线，例如:广东省广州市
  private function _getRegionLine($dqID,$type=0) {
    $m = M();
    $sql = 'select t1.id as did, t1.title as dtitle, t2.id, t2.title
      from a_region t1 left join a_region t2 on (t1.id = t2.did)
      where t2.id = '.$dqID;
    $list = $m->query($sql);
    $region = $list[0];
    if ($type == 1) return $region['did'];
    if ($region['dtitle'] == $region['title']) $rt = $region['dtitle'];
    else $rt = $region['dtitle'].' '.$region['title'];
    return $rt;
  }
  
  private function _getAttachMents($id){
     $m=M('AAttachments');
	 $bak=$m->where("type='require' and related_id={$id}")->select();
	 //echo $m->getLastSQL();
	 return $bak;
  }


}
?>